<template>
	<view class="profile-container">
		<view class="header">
			<text class="title">完善个人资料</text>
		</view>

		<view class="content">
			<!-- 头像选择 -->
			<view class="form-item">
				<text class="label">头像</text>
				<view class="avatar-section">
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image class="avatar" :src="avatarUrl"></image>
					</button>
				</view>
			</view>

			<!-- 昵称 -->
			<view class="form-item">
				<text class="label">昵称</text>
				<input type="nickname" class="nickname-input" v-model="nickname" placeholder="请输入昵称" />
			</view>

			<!-- 性别 -->
			<view class="form-item">
				<text class="label">性别</text>
				<view class="gender-selector">
					<view class="gender-item" :class="{ active: gender === 'male' }" @click="selectGender('male')">
						<text>男</text>
					</view>
					<view class="gender-item" :class="{ active: gender === 'female' }" @click="selectGender('female')">
						<text>女</text>
					</view>
				</view>
			</view>

			<!-- 出生年份 -->
			<view class="form-item">
				<text class="label">出生年份</text>
				<view class="year-picker-container" @click="showYearPicker">
					<text class="year-text">{{ birthYear || '请选择' }}</text>
					<view class="arrow"></view>
				</view>
			</view>

			<!-- 所在地址 -->
			<view class="form-item">
				<text class="label">所在地址</text>
				<view class="address-picker-container" @click="showAddressPicker">
					<text class="address-text">{{ address || '请选择' }}</text>
					<view class="arrow"></view>
				</view>
				<button class="location-btn" @click.stop="getCurrentLocation">获取当前位置</button>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-section">
				<button class="submit-btn" @click="submitProfile">保存</button>
			</view>
		</view>

		<!-- 年份选择器弹出层 -->
		<view class="picker-modal" v-if="showYearModal" @click="hideYearPicker">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<text class="cancel-btn" @click="hideYearPicker">取消</text>
					<text class="confirm-btn" @click="confirmYear">确定</text>
				</view>
				<view class="picker-body">
					<picker-view class="year-picker" :value="[yearIndex]" :range="years" @change="onYearChange">
						<picker-view-column>
							<view class="year-item" v-for="item in years" :key="item">{{ item }}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</view>

		<!-- 地址选择器弹出层 -->
		<view class="picker-modal" v-if="showAddressModal" @click="hideAddressPicker">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<text class="cancel-btn" @click="hideAddressPicker">取消</text>
					<text class="confirm-btn" @click="confirmAddress">确定</text>
				</view>
				<view class="picker-body">
					<picker-view class="address-picker" :value="[addressIndex]" :range="addresses"
						@change="onAddressChange">
						<picker-view-column>
							<view class="address-item" v-for="item in addresses" :key="item">{{ item }}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 默认头像地址
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

// 生成年份数组（1950年到2023年）
const generateYears = () => {
	const years = [];
	const currentYear = new Date().getFullYear();
	for (let year = 1950; year <= currentYear; year++) {
		years.push(year.toString());
	}
	return years.reverse();
};

// 地址数组
const addressArray = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '南京', '西安', '重庆', '天津', '苏州', '长沙', '青岛', '郑州', '大连', '厦门', '哈尔滨', '沈阳', '长春'];

// 响应式数据
const nickname = ref('');
const gender = ref('');
const birthYear = ref('');
const address = ref('');
const avatarUrl = ref(defaultAvatarUrl);
// 标记当前头像是否为微信头像
const isWechatAvatar = ref(false);

// 年份选择器数据
const years = ref(generateYears());
const yearIndex = ref(0);
const showYearModal = ref(false);

// 地址选择器数据
const addresses = ref(addressArray);
const addressIndex = ref(0);
const showAddressModal = ref(false);

// 初始化用户信息
onLoad(() => {
	const userInfo = uni.getStorageSync('userInfo') || {};
	if (userInfo.nickname) {
		nickname.value = userInfo.nickname;
	}
	if (userInfo.gender) {
		// 将数字类型的性别值转换回字符串
		gender.value = userInfo.gender === 1 ? 'male' : userInfo.gender === 2 ? 'female' : '';
	}
	if (userInfo.birthYear) {
		birthYear.value = userInfo.birthYear;
	}
	if (userInfo.address) {
		address.value = userInfo.address;
	}
	if (userInfo.avatar && userInfo.avatar !== '/static/logo.png') {
		avatarUrl.value = userInfo.avatar;
		// 判断并设置头像是否为微信头像
		isWechatAvatar.value = userInfo.avatar.indexOf('wx.qlogo.cn') !== -1;
	}
});

// 选择性别
const selectGender = (selectedGender) => {
	gender.value = selectedGender;
};

// 显示年份选择器
const showYearPicker = () => {
	showYearModal.value = true;
	// 如果已有选择的年份，设置选择器的默认值
	if (birthYear.value) {
		const index = years.value.findIndex(year => year === birthYear.value);
		if (index !== -1) {
			yearIndex.value = index;
		}
	}
};

// 隐藏年份选择器
const hideYearPicker = () => {
	showYearModal.value = false;
};

// 年份选择器变化
const onYearChange = (e) => {
	yearIndex.value = e.detail.value[0];
};

// 确认年份选择
const confirmYear = () => {
	birthYear.value = years.value[yearIndex.value];
	showYearModal.value = false;
};

// 显示地址选择器
const showAddressPicker = () => {
	showAddressModal.value = true;
	// 如果已有选择的地址，设置选择器的默认值
	if (address.value) {
		const index = addresses.value.findIndex(item => item === address.value);
		if (index !== -1) {
			addressIndex.value = index;
		}
	}
};

// 隐藏地址选择器
const hideAddressPicker = () => {
	showAddressModal.value = false;
};

// 地址选择器变化
const onAddressChange = (e) => {
	addressIndex.value = e.detail.value[0];
};

// 确认地址选择
const confirmAddress = () => {
	address.value = addresses.value[addressIndex.value];
	showAddressModal.value = false;
};

// 获取用户当前位置
const getCurrentLocation = () => {
	uni.showLoading({
		title: '定位中...'
	});

	// 调用uni-app的获取位置API
	uni.getLocation({
		type: 'gcj02',
		geocode: true,
		success: (res) => {
			uni.hideLoading();
			console.log('获取位置成功:', res);

			// 方案1: 如果有地址信息，直接使用
			if (res.address && (res.address.city || res.address.district || res.address.province)) {
				// 提取城市信息
				const city = res.address.city || res.address.district || res.address.province;
				address.value = city;

				// 检查是否在现有地址列表中
				const index = addresses.value.indexOf(city);
				if (index !== -1) {
					addressIndex.value = index;
				} else {
					// 如果不在列表中，添加到列表并选中
					addresses.value.push(city);
					addressIndex.value = addresses.value.length - 1;
				}
			}
			// 方案2: 如果只有经纬度，使用位置选择器让用户确认位置
			else if (res.latitude && res.longitude) {
				uni.chooseLocation({
					latitude: res.latitude,
					longitude: res.longitude,
					success: (chooseRes) => {
						console.log('选择位置成功:', chooseRes);
						// 从选择的位置中提取城市信息
						let cityName = chooseRes.name; // 默认使用地点名称
						// 尝试从地址字符串中提取城市信息
						if (chooseRes.address) {
							const cityMatch = chooseRes.address.match(/[\u4e00-\u9fa5]{2,5}(?:市|区|县)/);
							if (cityMatch) {
								cityName = cityMatch[0];
							}
						}

						address.value = cityName;
						// 检查是否在现有地址列表中
						const index = addresses.value.indexOf(cityName);
						if (index !== -1) {
							addressIndex.value = index;
						} else {
							// 如果不在列表中，添加到列表并选中
							addresses.value.push(cityName);
							addressIndex.value = addresses.value.length - 1;
						}
					},
					fail: (chooseErr) => {
						console.error('选择位置失败:', chooseErr);
						uni.showToast({
							title: '获取具体位置失败',
							icon: 'none'
						});
					}
				});
			}
			// 方案3: 如果都没有，显示错误提示
			else {
				uni.showToast({
					title: '未获取到地址信息',
					icon: 'none'
				});
			}
		},
		fail: (err) => {
			uni.hideLoading();
			console.error('获取位置失败:', err);

			// 显示错误提示
			let errorMsg = '获取位置失败，请检查定位权限';
			if (err.errMsg.indexOf('auth deny') !== -1) {
				errorMsg = '请在设置中开启定位权限';
			}

			uni.showToast({
				title: errorMsg,
				icon: 'none'
			});
		}
	});
};

// 微信头像选择回调
const onChooseAvatar = (e) => {
	console.log('选择头像结果:', e);

	const { avatarUrl: newAvatarUrl } = e.detail;
	avatarUrl.value = newAvatarUrl;
	// 记录用户是否选择了微信头像，用于后续处理
	isWechatAvatar.value = newAvatarUrl.indexOf('wx.qlogo.cn') !== -1;
};



// 提交个人资料
const submitProfile = async () => {
	// 验证表单
	if (!nickname.value) {
		uni.showToast({
			title: '请输入昵称',
			icon: 'none'
		});
		return;
	}

	if (!gender.value) {
		uni.showToast({
			title: '请选择性别',
			icon: 'none'
		});
		return;
	}

	if (!birthYear.value) {
		uni.showToast({
			title: '请选择出生年份',
			icon: 'none'
		});
		return;
	}

	if (!address.value) {
		uni.showToast({
			title: '请选择所在地址',
			icon: 'none'
		});
		return;
	}

	// 提交资料到云端
	uni.showLoading({
		title: '保存中...'
	});

	// 准备提交的数据
	const userInfo = uni.getStorageSync('userInfo') || {};
	// 将字符串性别值转换为数字类型
	let genderNum = 0; // 默认未知
	if (gender.value === 'male') {
		genderNum = 1; // 男
	} else if (gender.value === 'female') {
		genderNum = 2; // 女
	}

	// 从本地存储单独获取token和过期时间
	const storedToken = uni.getStorageSync('token');
	const tokenExpired = uni.getStorageSync('tokenExpired');
	const currentTime = Date.now();

	// 打印调试信息，检查token和过期时间
	console.log('当前token:', storedToken);
	console.log('存储的tokenExpired:', tokenExpired);
	console.log('当前时间:', currentTime);

	// 检查token是否存在或已过期
	// 处理可能的时间单位不匹配问题（秒 vs 毫秒）
	let isTokenExpired = false;
	if (tokenExpired) {
		// 如果tokenExpired是数字类型且长度小于13位，可能是秒级时间戳，需要转换为毫秒
		if (typeof tokenExpired === 'number' && tokenExpired.toString().length < 13) {
			isTokenExpired = currentTime > (tokenExpired * 1000);
		} else {
			isTokenExpired = currentTime > tokenExpired;
		}
	}

	if (!storedToken || storedToken === '' || isTokenExpired) {
		uni.hideLoading();
		uni.showToast({
			title: '登录已过期，请重新登录',
			icon: 'none'
		});
		// 延迟跳转，让用户看到提示
		setTimeout(() => {
			// 跳转到登录页面或首页
			uni.redirectTo({
				url: '/pages/index/index'
			});
		}, 1500);
		return;
	}

	const userData = {
		nickname: nickname.value,
		gender: genderNum, // 使用数字类型的性别值
		dob: birthYear.value,
		location: address.value,
		token: storedToken // 使用单独存储的token
	};

	// 处理头像上传逻辑
	if (avatarUrl.value && avatarUrl.value !== defaultAvatarUrl) {
		// 区分微信头像和本地头像
		if (isWechatAvatar.value || avatarUrl.value.indexOf('wx.qlogo.cn') !== -1) {
			console.log('使用微信头像:', avatarUrl.value);
			// 微信头像直接使用，不需要上传
			userData.avatar = avatarUrl.value;
		} else if (avatarUrl.value.indexOf('blob:') === -1) {
			// 非微信头像且不是临时blob地址，需要上传
			console.log('准备上传本地头像:', avatarUrl.value);

			try {
				// 提取文件扩展名，确保即使没有扩展名也能正常上传
				let fileExtension = 'jpg'; // 默认扩展名
				const extensionMatch = avatarUrl.value.match(/\.([^.]+)$/);
				if (extensionMatch && extensionMatch[1]) {
					fileExtension = extensionMatch[1].toLowerCase();
					// 确保是有效的图片格式
					const validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
					if (!validExtensions.includes(fileExtension)) {
						fileExtension = 'jpg';
					}
				}

				// 上传头像文件到云存储
				const uploadRes = await uniCloud.uploadFile({
					cloudPath: `avatars/${Date.now()}-${Math.random().toString(36).substring(2)}.${fileExtension}`,
					filePath: avatarUrl.value
				});

				if (uploadRes.fileID) {
					userData.avatar = uploadRes.fileID;
					// 同时更新avatarUrl，确保本地显示和保存都使用新上传的头像
					avatarUrl.value = uploadRes.fileID;
					console.log('头像上传成功，云存储地址:', uploadRes.fileID);
				} else {
					console.error('上传头像返回但没有fileID');
				}
			} catch (error) {
				console.error('上传头像失败:', error);
				uni.showToast({
					title: '上传头像失败，请重试',
					icon: 'none'
				});
				return;
			}
		} else if (avatarUrl.value.indexOf('http') === 0) {
			// 其他网络图片，直接使用
			console.log('使用网络头像:', avatarUrl.value);
			userData.avatar = avatarUrl.value;
		}
	}
	
	console.log('最终提交的用户数据:', userData);

	uniCloud.callFunction({
		name: 'update-user-profile', // 更明确的云函数名称
		data: userData,
		success: (res) => {
			uni.hideLoading();
			console.log('保存个人资料成功:', res);

			// 检查响应结果
			if (res.result && res.result.code === 0) {
				// 保存成功后，更新本地用户信息
				const userInfo = uni.getStorageSync('userInfo') || {};
				// 先保存我们需要设置的值
				const updatedInfo = {
					nickname: nickname.value,
					gender: genderNum, // 存储数字类型的性别值
					birthYear: birthYear.value,
					address: address.value,
					avatar: avatarUrl.value // 存储头像URL
				};

				// 如果有返回的用户信息，先合并到updatedInfo
				if (res.result.data && typeof res.result.data === 'object') {
					// 确保返回的数据不会覆盖我们手动设置的值
					Object.assign(updatedInfo, res.result.data);
					// 重新设置关键字段，确保不会被覆盖
					updatedInfo.gender = genderNum;
					updatedInfo.nickname = nickname.value;
					updatedInfo.avatar = avatarUrl.value;
				}

				// 将合并后的数据赋值给userInfo并保存
				// 确保所有字段都在顶层，而不是嵌套结构中
				Object.assign(userInfo, updatedInfo);
				// 特殊处理：如果userInfo中存在嵌套的userInfo对象，我们需要将它展开
				if (userInfo.userInfo && typeof userInfo.userInfo === 'object') {
					// 先将嵌套的userInfo对象中的字段合并到顶层
					Object.assign(userInfo, userInfo.userInfo);
					// 删除嵌套的userInfo对象
					delete userInfo.userInfo;
				}
				uni.setStorageSync('userInfo', userInfo);

				// 调试信息
				console.log('保存到本地的用户信息:', userInfo);
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				});

				// 返回首页
				setTimeout(() => {
					// 改为跳转到个人中心页面
				uni.switchTab({
					url: '/pages/center/index'
				});
				}, 1500);
			} else {
				// 后端返回了错误信息
				uni.showToast({
					title: res.result.message || '保存失败，请重试',
					icon: 'none'
				});
			}
		},
		fail: (err) => {
			uni.hideLoading();
			console.error('保存个人资料失败:', err);
			// 根据错误类型提供更具体的提示
			let errorMsg = '网络错误，请稍后重试';
			if (err.errMsg && err.errMsg.includes('timeout')) {
				errorMsg = '请求超时，请检查网络连接';
			} else if (err.errMsg && err.errMsg.includes('auth')) {
				errorMsg = '登录已过期，请重新登录';
			}
			uni.showToast({
				title: errorMsg,
				icon: 'none'
			});
			// 如果是token相关错误，清除本地存储并跳转到登录页
			// 检查多种可能的错误格式
			let hasTokenError = false;
			if (err.result && (err.result.code === 30202 || err.result.code === 30203)) {
				hasTokenError = true;
			} else if (err.code === 30202 || err.code === 30203) {
				hasTokenError = true;
			}
			if (hasTokenError) {
				// 清除本地存储的token和用户信息
				uni.removeStorageSync('token');
				uni.removeStorageSync('tokenExpired');
				uni.removeStorageSync('userInfo');
				// 延迟跳转，让用户看到提示
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/index/index'
					});
				}, 1500);
			}
		}
	});
};
</script>

<style scoped>
.profile-container {
	padding: 30rpx;
	min-height: 100vh;
	background-color: #f7f7f7;
}

.header {
	text-align: center;
	margin-bottom: 60rpx;
}

.title {
	font-size: 44rpx;
	font-weight: bold;
	color: #333;
}

.content {
	background-color: white;
	padding: 40rpx;
	border-radius: 20rpx;
}

/* 表单样式 */
.form-item {
	margin-bottom: 40rpx;
}

.label {
	display: block;
	font-size: 32rpx;
	color: #333;
	margin-bottom: 20rpx;
}

/* 头像样式 */
.avatar-section {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-bottom: 40rpx;
}

.avatar-wrapper {
	width: 200rpx;
	height: 200rpx;
	border-radius: 50%;
	padding: 0;
	border: 2rpx solid #eee;
	overflow: hidden;
	display: flex;
	justify-content: center;
	align-items: center;
}

.avatar {
	width: 100%;
	height: 100%;
}

/* 昵称输入框样式 */
.nickname-input {
	width: 100%;
	height: 88rpx;
	border: 2rpx solid #eee;
	border-radius: 10rpx;
	padding: 0 20rpx;
	font-size: 32rpx;
}

/* 性别选择器样式 */
.gender-selector {
	display: flex;
	gap: 40rpx;
}

.gender-item {
	width: 120rpx;
	height: 70rpx;
	border: 2rpx solid #ddd;
	border-radius: 10rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
	color: #666;
}

.gender-item.active {
	border-color: #007aff;
	color: #007aff;
}

/* 年份选择器样式 */
.year-picker-container,
.address-picker-container {
	width: 100%;
	height: 88rpx;
	border: 2rpx solid #eee;
	border-radius: 10rpx;
	padding: 0 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 32rpx;
	color: #666;
}

.arrow {
	width: 20rpx;
	height: 20rpx;
	border-top: 2rpx solid #ccc;
	border-right: 2rpx solid #ccc;
	transform: rotate(45deg);
}

/* 年份选择器弹出层样式 */
.picker-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: flex-end;
	align-items: flex-end;
	z-index: 999;
}

.picker-content {
	width: 100%;
	background-color: white;
	border-radius: 20rpx 20rpx 0 0;
}

.picker-header {
	display: flex;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
}

.picker-header .cancel-btn,
.picker-header .confirm-btn {
	font-size: 32rpx;
	padding: 0 20rpx;
}

.picker-header .cancel-btn {
	color: #666;
}

.picker-header .confirm-btn {
	color: #007aff;
	font-weight: bold;
}

.picker-body {
	padding: 20rpx 0;
}

.year-picker {
	width: 100%;
	height: 400rpx;
}

.address-picker {
	width: 100%;
	height: 400rpx;
}

.year-item,
.address-item {
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	font-size: 32rpx;
}

/* 提交按钮样式 */
.submit-section {
	margin-top: 60rpx;
}

.submit-btn {
	width: 100%;
	height: 90rpx;
	background-color: #007aff;
	color: white;
	font-size: 36rpx;
	border-radius: 10rpx;
}

/* 获取当前位置按钮样式 */
.location-btn {
	margin-top: 20rpx;
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
	background-color: #e8f4fd;
	color: #409eff;
	border-radius: 10rpx;
	border: 1rpx solid #409eff;
}
</style>